package cn.lg.soar.system.general.service.impl;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.current.CurrentProxy;
import cn.lg.soar.database.base.service.impl.BaseServiceImpl;
import cn.lg.soar.system.general.entity.UserConfig;
import cn.lg.soar.system.general.entity.UserConfigGroup;
import cn.lg.soar.system.general.mapper.UserConfigMapper;
import cn.lg.soar.system.general.service.IUserConfigGroupService;
import cn.lg.soar.system.general.service.IUserConfigService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户配置
 * @author luguoxiang
 * @since 2023-07-13
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@CacheConfig(cacheNames = "ucfg")
public class UserConfigServiceImpl extends BaseServiceImpl<UserConfigMapper, UserConfig> implements IUserConfigService, CurrentProxy<IUserConfigService> {

    @Autowired
    private IUserConfigGroupService definitionService;

    @Cacheable(key = "#code+':'+#userId")
    @Override
    public String get(long userId, String code) {
        return baseMapper.getConfig(userId, code);
    }

    @Override
    public Map<String, String> map(long userId, String[] codes) {
        Map<String, String> map = new HashMap<>(codes.length);
        IUserConfigService proxy = proxy();
        for (String code : codes) {
            map.put(code, proxy.get(userId, code));
        }
        return map;
    }

    @CacheEvict(key = "#code+':'+#userId")
    @Override
    public boolean set(long userId, String code, String value) {
        // 必须先由管理员定义配置
        UserConfigGroup group = definitionService.getByCode(code);
        AssertUtil.notNull(group, "配置未定义");
        Integer groupId = group.getId();
        // 查id
        Long id = getObj(
                Wrappers.<UserConfig>lambdaQuery()
                        .select(UserConfig::getId)
                        .eq(UserConfig::getGroupId, groupId)
                        .eq(UserConfig::getUserId, userId),
                x -> Long.parseLong(x.toString())
        );
        UserConfig config = new UserConfig();
        if (id == null) {
            // 新增
            config.setGroupId(groupId);
            config.setUserId(userId);
            config.setValue(value);
            return save(config);
        }
        // 更新
        config.setId(id);
        config.setValue(value);
        return updateById(config);
    }
}
